# -*- coding: utf-8 -*-
"""
Created on Sun Nov 13 10:27:38 2022

@author: LUO
"""
import sys
from PyQt5 import QtCore, QtWidgets
from ui_keyboard import Ui_keyboard

class NumKeyBoard(QtWidgets.QMainWindow, Ui_keyboard):
   def __init__(self, callback=None, parent=None):
      super(NumKeyBoard, self).__init__(parent)
      self.setupUi(self)

      self.setWindowFlags(QtCore.Qt.FramelessWindowHint|QtCore.Qt.WindowCloseButtonHint)
      # self.setWindowFlags(Qt.FramelessWindowHint)
      self.setWindowModality(QtCore.Qt.ApplicationModal)

      self.setWindowModality(QtCore.Qt.ApplicationModal)

      self.cb = callback
      self.keys = ''

      self.setupListner()

   def setupListner(self):
      self.Btn_0.clicked.connect(lambda: self.btnClicked(self.Btn_0))
      self.Btn_1.clicked.connect(lambda: self.btnClicked(self.Btn_1))
      self.Btn_2.clicked.connect(lambda: self.btnClicked(self.Btn_2))
      self.Btn_3.clicked.connect(lambda: self.btnClicked(self.Btn_3))
      self.Btn_4.clicked.connect(lambda: self.btnClicked(self.Btn_4))
      self.Btn_5.clicked.connect(lambda: self.btnClicked(self.Btn_5))
      self.Btn_6.clicked.connect(lambda: self.btnClicked(self.Btn_6))
      self.Btn_7.clicked.connect(lambda: self.btnClicked(self.Btn_7))
      self.Btn_8.clicked.connect(lambda: self.btnClicked(self.Btn_8))
      self.Btn_9.clicked.connect(lambda: self.btnClicked(self.Btn_9))
      self.Btn_dot.clicked.connect(lambda: self.btnClicked(self.Btn_dot))
      self.Btn_back.clicked.connect(self.btn_backspace_clicked)
      self.Btn_ok.clicked.connect(self.btn_ok_clicked)

   def btnClicked(self, button):
      self.keys += button.text()
      self.reflect_keys()

   def reflect_keys(self):
      self.edit_text.setText(self.keys)
      self.edit_text.setFocus()
      if self.cb is not None:
         if len(self.keys) == 0:
            self.cb.on_key("0")
         else:
            self.cb.on_key(self.keys)

   def btn_backspace_clicked(self):
      self.keys = self.keys[:-1]
      self.reflect_keys()

   def btn_ok_clicked(self):
      self.keys = ''
      self.edit_text.clear()
      self.hide()

class MainKeyTest(QtWidgets.QMainWindow):

   def __init__(self, parent=None):
      super(MainKeyTest, self).__init__(parent)
      self.resize(600,200)

      self.kb = NumKeyBoard(callback=self)
      self.focused_input = None

      self.input = QtWidgets.QLineEdit(self)
      self.input.setGeometry(QtCore.QRect(30, 60, 500, 50))
      self.input.mousePressEvent = self.lineEdit_clicked

   def lineEdit_clicked(self, e):
      self.focused_input = self.input
      self.kb.show()

   def on_key(self, keys):
      if self.focused_input is not None:
         self.focused_input.setText(keys)

if __name__ == "__main__":
   app = QtWidgets.QApplication(sys.argv)
   m_window = MainKeyTest(None)
   m_window.show()

   app.exec()
